using MediatR;
using ProduceBasicData.Api.Application.Command.Material.MaterialGroup;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.MaterialGroup
{
    /// <summary>
    /// 物料群组查询处理类
    /// </summary>
    public class GetMaterialGroupHandler : IRequestHandler<GetMaterialGroupCommand, ApiPaging<MaterialGroupDTO>>
    {
        private readonly IBaseRespository<MaterialGroupModel> materialGroupRepository;
        private readonly IBaseRespository<GroupTypeDictionary> groupTypeRepository;
        private readonly IBaseRespository<CraftModel> craftRepository;

        public GetMaterialGroupHandler(
            IBaseRespository<MaterialGroupModel> materialGroupRepository,
            IBaseRespository<GroupTypeDictionary> groupTypeRepository,
            IBaseRespository<CraftModel> craftRepository)
        {
            this.materialGroupRepository = materialGroupRepository;
            this.groupTypeRepository = groupTypeRepository;
            this.craftRepository = craftRepository;
        }

        public Task<ApiPaging<MaterialGroupDTO>> Handle(GetMaterialGroupCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<MaterialGroupDTO>();

            try
            {
                // 获取物料群组数据
                var materialGroups = materialGroupRepository.GetAll().Where(x => !x.Isdel);
                var groupTypes = groupTypeRepository.GetAll().Where(x => !x.Isdel);
                var crafts = craftRepository.GetAll().Where(x => !x.Isdel);

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.MaterialNo))
                {
                    materialGroups = materialGroups.Where(x => x.MaterialNo.Contains(request.MaterialNo));
                }

                if (!string.IsNullOrEmpty(request.MaterialName))
                {
                    materialGroups = materialGroups.Where(x => x.MaterialName.Contains(request.MaterialName));
                }

                if (request.GroupTypeId.HasValue)
                {
                    materialGroups = materialGroups.Where(x => x.GroupTypeId == request.GroupTypeId.Value);
                }

                if (request.GroupId.HasValue)
                {
                    materialGroups = materialGroups.Where(x => x.GroupId == request.GroupId.Value);
                }

                // 联表查询
                var query = from mg in materialGroups
                           join gt in groupTypes on mg.GroupTypeId equals gt.Id into groupTypeGroup
                           from groupType in groupTypeGroup.DefaultIfEmpty()
                           join c in crafts on mg.DefaultCraftId equals c.Id into craftGroup
                           from craft in craftGroup.DefaultIfEmpty()
                           select new MaterialGroupDTO
                           {
                               Id = mg.Id,
                               MaterialNo = mg.MaterialNo,
                               MaterialName = mg.MaterialName,
                               GroupTypeId = mg.GroupTypeId,
                               GroupType = groupType != null ? groupType.GroupTypeName : mg.GroupType,
                               GroupId = mg.GroupId,
                               GroupName = mg.GroupName,
                               DefaultCraftId = mg.DefaultCraftId,
                               DefaultCraftName = craft != null ? craft.CraftName : mg.DefaultCraftName,
                               MaterialDesc = mg.MaterialDesc,
                               CreateName = mg.CreateName,
                               CreateTime = mg.CreateTime,
                               UpdateName = mg.UpdateName,
                               UpdateTime = mg.UpdateTime
                           };

                // 分页处理
                result.PageDatas = query
                    .OrderByDescending(x => x.CreateTime)
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList();

                result.TotalCount = query.Count();
                result.Code = ApiEnum.Success;
                result.Msg = "物料群组查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"物料群组查询异常：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
}
